package com.pay.alipay;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayFundBatchTransferRequest;
import com.alipay.api.response.AlipayFundBatchTransferResponse;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

public class AliPayFundTransfer {


    private AliConfig aliPayConfig;

    public AliPayFundTransfer(AliConfig aliPayConfig) {
        this.aliPayConfig = aliPayConfig;
    }

    /**
     * 支付宝资金转账
     *
     * @param outBizNo 订单流水号
     * @param amount   金额
     * @param account  账号（支付宝登录账号/手机号或者邮箱）
     * @param realName 真实姓名
     * @param remark   备注
     * @param title    转账头信心
     * @return
     * @throws AlipayApiException
     */
    public Map<String, Object> fundTransfer(String outBizNo, BigDecimal amount, String account, String realName, String remark, String title) throws AlipayApiException {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
                aliPayConfig.appid(),
                aliPayConfig.private_key(),
                "JSON", "UTF-8",
                aliPayConfig.alipay_public_key(), "RSA2");
        AlipayFundBatchTransferRequest request = new AlipayFundBatchTransferRequest();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("out_biz_no", outBizNo);
        paramMap.put("trans_amount", amount);
        paramMap.put("product_code", "TRANS_ACCOUNT_NO_PWD");
        paramMap.put("biz_scene", "DIRECT_TRANSFER");
        paramMap.put("order_title", title);
        Map<String, Object> payee_info = new HashMap<>();
        payee_info.put("identity", account);
        payee_info.put("identity_type", "ALIPAY_LOGON_ID");
        payee_info.put("name", realName);
        paramMap.put("payee_info", JSONObject.toJSONString(payee_info));
        paramMap.put("remark", remark);
        request.setBizContent(JSONObject.toJSONString(paramMap));
        AlipayFundBatchTransferResponse execute = alipayClient.execute(request);
        String body = execute.getBody();
        System.out.println(body);
        return JSONObject.parseObject(body);

    }
}
